import { defineStore } from 'pinia';
import axios from 'axios';
import CryptoJS from 'crypto-js';
const BASE_URL = import.meta.env.VITE_API_BASE_URL;
axios.defaults.timeout = 42000;
axios.defaults.headers['authorization'] = CryptoJS.MD5(
  'renser_ying_guang_me'
).toString();

import {
  formatHighPriceSort,
  formatLowPriceSort,
  findMostFrequent
} from '../method/index.js';

export const stockStore = defineStore('stock', {
  state: () => ({
    isLoading: true,
    isSort: false,
    isFilter: false,
    allTopGainers: [],
    allTopLosers: [],
    allRecommendations: [],
    topGainers: [],
    topLosers: [],
    recommendations: [],
    inputFilter: '',
    priceFilter: '',
    priceList: [
      { name: '1元以下', value: '0,1' },
      { name: '1-5元', value: '1,5' },
      { name: '5-10元', value: '5,10' },
      { name: '10-20元', value: '10,20' },
      { name: '20-40元', value: '20,40' },
      { name: '40-60元', value: '40,60' },
      { name: '60-100元', value: '60,100' },
      { name: '100-200元', value: '100,200' },
      { name: '200-500元', value: '200,500' },
      { name: '500元以上', value: '500,10000' }
    ],
    marketFilter: '',
    marketList: [
      { name: '沪市主板', value: '60' },
      { name: '深市主板', value: '00' },
      { name: '科创板', value: '68' },
      { name: '创业板', value: '30' }
    ],
    sectorFilter: '',
    sectorList: [],
    conceptFilter: '',
    conceptList: [],
    newConceptList: [],
    buySellFilter: '',
    historicalPredictions: [],
    totalShare: 0,
  }),
  actions: {
    // 排序状态更新
    updateSort(sortable) {
      this.isSort = sortable;
    },
    // 更新股票名称过滤条件
    updateNameFilter(value) {
      this.inputFilter = value;
      if (value) {
        this.priceFilter = '';
        this.marketFilter = '';
        this.sectorFilter = '';
        this.conceptFilter = '';
        this.buySellFilter = '';
        this.topGainers = this.allTopGainers.filter(
          (item) =>
            item.code.indexOf(value) !== -1 || item.name.indexOf(value) !== -1
        );

        this.topLosers = this.allTopLosers.filter(
          (item) =>
            item.code.indexOf(value) !== -1 || item.name.indexOf(value) !== -1
        );
      } else {
        this.topGainers = this.allTopGainers;
        this.topLosers = this.allTopLosers;
      }
    },
    // 更新主力吸筹过滤条件
    updateMainFilter() {
      this.topGainers = this.topGainers.filter(
        (item) => item.f84 < 0 && item.f72 + item.f66 > 0 && item.f66 > 1e7 && item.mainMoneyNet > 1e7
      );
      this.topLosers = this.topLosers.filter(
        (item) => item.f84 < 0 && item.f72 + item.f66 > 0 && item.f66 > 1e7 && item.mainMoneyNet > 1e7
      );
    },
    // 更新价格过滤条件
    updatePriceFilter(value) {
      this.priceFilter = value;
      this.updateFilter(value);
    },
    // 更新市场过滤条件
    updateMarketFilter(value) {
      this.marketFilter = value;
      this.updateFilter(value);
    },
    // 更新板块过滤条件
    updateSectorFilter(value) {
      this.sectorFilter = value;
      this.updateFilter(value);
    },
    // 更新概念过滤条件
    updateConceptFilter(value) {
      this.conceptFilter = value;
      this.updateFilter(value);
    },
    // 高抛低吸
    updateBuySellFilter(value) {
      this.buySellFilter = value;
      this.updateFilter(value);
    },
    // 更新过滤数据
    updateFilter(value) {
      if (value) {
        this.isFilter = true;
        this.isSort = true;
      } else {
        this.isFilter = false;
        this.isSort = false;
      }
      this.filterGainer();
      this.filterLosers();
      this.filterRecommendations();
    },
    // 过滤涨幅榜数据
    filterGainer() {
      let filter0Data = this.allTopGainers;
      if (this.buySellFilter === '1') {
        filter0Data = this.allTopGainers.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.lowPrice &&
            item.lowPrice.length === 3 &&
            item.lowPrice[2] > item.price
        );
      } else if (this.buySellFilter === '2') {
        filter0Data = this.allTopGainers.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.highPrice &&
            item.highPrice.length === 3 &&
            item.highPrice[1] < item.price
        );
      } else if (this.buySellFilter === '3') {
        filter0Data = this.allTopGainers.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.highPrice &&
            item.highPrice.length === 3 &&
            item.lowPrice &&
            item.lowPrice.length === 3 &&
            item.price > item.lowPrice[2] &&
            item.price < item.highPrice[1]
        );
      }

      let filter1Data = this.sectorFilter
        ? filter0Data.filter(
          (item) => item.sector.indexOf(this.sectorFilter) !== -1
        )
        : filter0Data;

      let filter2Data = this.conceptFilter
        ? filter1Data.filter(
          (item) => item.concept.indexOf(this.conceptFilter) !== -1
        )
        : filter1Data;

      let filter3Data = this.marketFilter
        ? filter2Data.filter((item) => item.code.startsWith(this.marketFilter))
        : filter2Data;

      this.topGainers = this.priceFilter
        ? filter3Data.filter(
          (item) =>
            item.price >= this.priceFilter.split(',')[0] &&
            item.price < this.priceFilter.split(',')[1]
        )
        : filter3Data;
    },
    // 过滤跌幅榜数据
    filterLosers() {
      let filter0Data = this.allTopLosers;
      if (this.buySellFilter === '1') {
        filter0Data = this.allTopLosers.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.lowPrice &&
            item.lowPrice.length === 3 &&
            item.lowPrice[2] > item.price
        );
      } else if (this.buySellFilter === '2') {
        filter0Data = this.allTopLosers.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.highPrice &&
            item.highPrice.length === 3 &&
            item.highPrice[1] < item.price
        );
      } else if (this.buySellFilter === '3') {
        filter0Data = this.allTopLosers.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.highPrice &&
            item.highPrice.length === 3 &&
            item.lowPrice &&
            item.lowPrice.length === 3 &&
            item.price > item.lowPrice[2] &&
            item.price < item.highPrice[1]
        );
      }

      let filter1Data = this.sectorFilter
        ? filter0Data.filter(
          (item) => item.sector.indexOf(this.sectorFilter) !== -1
        )
        : filter0Data;

      let filter2Data = this.conceptFilter
        ? filter1Data.filter(
          (item) => item.concept.indexOf(this.conceptFilter) !== -1
        )
        : filter1Data;

      let filter3Data = this.marketFilter
        ? filter2Data.filter((item) => item.code.startsWith(this.marketFilter))
        : filter2Data;

      this.topLosers = this.priceFilter
        ? filter3Data.filter(
          (item) =>
            item.price >= this.priceFilter.split(',')[0] &&
            item.price < this.priceFilter.split(',')[1]
        )
        : filter3Data;
    },
    // 过滤推荐榜数据
    filterRecommendations() {
      let filter0Data = this.allRecommendations;
      if (this.buySellFilter === '1') {
        filter0Data = this.allRecommendations.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.lowPrice &&
            item.lowPrice.length === 3 &&
            item.lowPrice[2] > item.price
        );
      } else if (this.buySellFilter === '2') {
        filter0Data = this.allRecommendations.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.highPrice &&
            item.highPrice.length === 3 &&
            item.highPrice[1] < item.price
        );
      } else if (this.buySellFilter === '3') {
        filter0Data = this.allRecommendations.filter(
          (item) =>
            item.name.indexOf('ST') === -1 &&
            item.highPrice &&
            item.highPrice.length === 3 &&
            item.lowPrice &&
            item.lowPrice.length === 3 &&
            item.price > item.lowPrice[2] &&
            item.price < item.highPrice[1]
        );
      }

      let filterData = this.sectorFilter
        ? filter0Data.filter(
          (item) => item.sector.indexOf(this.sectorFilter) !== -1
        )
        : filter0Data;

      this.recommendations = this.conceptFilter
        ? filterData.filter(
          (item) => item.concept.indexOf(this.conceptFilter) !== -1
        )
        : filterData;
    },
    // 获取股票数据
    async fetchStockData() {
      try {
        const { data } = await axios.get(`${BASE_URL}/api/stocks`);
        const { topGainers, topLosers, recommendations } = data;
        if (topGainers.length > 0) {
          this.isLoading = false;
        }

        if (topGainers.length > 0 && !this.isSort) {
          this.allTopGainers = topGainers;
          if (this.inputFilter) {
            this.updateNameFilter(this.inputFilter);
          } else {
            this.filterGainer();
          }
        }
        if (topLosers.length > 0 && !this.isSort) {
          this.allTopLosers = topLosers;
          if (this.inputFilter) {
            this.updateNameFilter(this.inputFilter);
          } else {
            this.filterLosers();
          }
        }
        if (recommendations.length > 0 && !this.isSort) {
          this.allRecommendations = recommendations;
          this.filterRecommendations();
        }

        this.totalShare =
          this.allTopGainers.reduce((acc, item) => acc + item.marketValue, 0) +
          this.allTopLosers.reduce((acc, item) => acc + item.marketValue, 0);
      } catch (error) {
        this.isLoading = false;
        console.error('获取股票数据失败:', error);
      }
    },
    // 获取板块信息
    async getSectorList() {
      try {
        const { data } = await axios.get(`${BASE_URL}/api/sectorList`);
        this.sectorList = data;
      } catch (error) {
        console.error('获取板块信息失败:', error);
      }
    },
    // 获取概念信息
    async getConceptList() {
      try {
        const { data } = await axios.get(`${BASE_URL}/api/conceptList`);
        this.conceptList = data;
      } catch (error) {
        console.error('获取概念信息失败:', error);
      }
    },
    // 获取新概念信息
    async getNewConceptList() {
      try {
        const { data } = await axios.get(`${BASE_URL}/api/newConceptList`);
        this.newConceptList = data;
      } catch (error) {
        console.error('获取新概念信息失败:', error);
      }
    },
    // 获取历史数据
    async fetchHistoryStockRecommendation(date) {
      try {
        const { data } = await axios.get(
          `${BASE_URL}/api/historyByDate/${date}`
        );
        this.historicalPredictions = data;
      } catch (error) {
        console.error('获取历史推荐股票失败:', error);
      }
    },
    // 根据股票编码获取股票信息
    async fetchStockByCodes(codes) {
      try {
        return await axios.post(`${BASE_URL}/api/stocks/codes`, {
          codes
        });
      } catch (error) {
        console.error('获取历史推荐股票失败:', error);
      }
    },
    // 获取股票近300天的数据 可以获取3年的数据
    async getHistoryStockPrice(code) {
      const params = {
        secid: `${code.startsWith('6') ? 1 : 0}.${code}`,
        fields1: 'f1,f2,f3,f4,f5,f6',
        fields2: 'f51,f52,f53,f54,f55,f56,f57,f58',
        klt: 101,
        fqt: 1,
        end: 20500101,
        lmt: 1000
      };

      const res = await axios.get(
        'https://push2his.eastmoney.com/api/qt/stock/kline/get',
        {
          params
        }
      );
      if (res.data.data && res.data.data.klines) {
        const klines = res.data.data.klines.reverse();
        const history = klines.map((line) => {
          // 日期，今开，今闭，今日最高，今日最低，震幅
          const [date, open, close, high, low, volume] = line.split(',');
          return {
            date,
            high,
            low,
            close
          };
        });

        let lowList = history.map((item) => item.low).reverse();
        let highList = history.map((item) => item.high).reverse();
        let closeList = history.map((item) => item.close).reverse();
        let dateList = history.map((item) => item.date).reverse();
        let lowPrice = formatLowPriceSort([...new Set(lowList)]);
        let highPrice = formatHighPriceSort([...new Set(highList)]);
        let mostPrice = findMostFrequent(closeList.slice(-200));
        this.updateHistoryStockPrice({
          code,
          lowPrice,
          highPrice
        });
        return {
          lowList,
          highList,
          closeList,
          dateList,
          lowPrice,
          highPrice,
          mostPrice
        };
      }
    },
    updateHistoryStockPrice(params) {
      axios.post(`${BASE_URL}/api/stocks/updatePrice`, params);
    }
  }
});
